import {loginAPI, logoutAPI} from '/src/api/login.js'
import {userListAPI, depListAPI, adminIndexAuthListAPI} from '/src/api/common.js'
import {resetRouter} from '/src/router/index.js'

import {adminUsersReadAPI} from '/src/api/user/personCenter.js'

import {addAuth, removeAuth} from '/src/utils/auth.js'
import {request} from '/src/utils/index.js'
import Lockr from 'lockr'
import {debounce} from 'throttle-debounce'
import {defineStore} from "pinia";


export const useErpUserStore = defineStore('erpUser', {
  state: () => ({
    userInfo: null, // 用户信息
    // 权限信息
    allAuth: null, // 总权限信息 默认空 调整动态路由
    userList: [], // 管理后台员工和部门
    deptList: [],
    crm: {
      "product":{"read":true,"transfer":true,"excelexport":true,"save":true,"update":true,"index":true,"excelimport":true,"delete":true,"status":true},
      "business":{"print":true,"read":true,"transfer":true,"teamsave":true,"excelexport":true,"save":true,"update":true,"index":true,"delete":true},
      "contract":{"discard":true,"print":true,"read":true,"transfer":true,"teamsave":true,
        "excelexport":true,"save":true,"update":true,"index":true,"delete":true},
      "pool":{"receive":true,"excelexport":true,"index":true,"distribute":true,"delete":true},
      "outwork":{"read":true,"save":true,"delete":true,"setting":true},
      "marketing":{"read":true,"updateStatus":true,"save":true,"index":true,"update":true,"delete":true},
      "receivablesPlan":{"read":true,"excelexport":true,"save":true,"update":true,"index":true,"delete":true},
      "leads":{"transform":true,"read":true,"transfer":true,"excelexport":true,"save":true,"update":true,"index":true,"excelimport":true,"delete":true},
      "receivables":{"print":true,"read":true,"transfer":true,"teamsave":true,"excelexport":true,"save":true,"update":true,"index":true,"delete":true},
      "visit":{"read":true,"save":true,"update":true,"index":true,"delete":true},
      "invoice":{"read":true,"transfer":true,"resetInvoiceStatus":true,"updateInvoiceStatus":true,"save":true,"update":true,"index":true,"delete":true},
      "followRecord":{"read":true,"excelexport":true,"save":true,"update":true,"excelimport":true,"delete":true},
      "contacts":{"read":true,"transfer":true,"teamsave":true,"excelexport":true,"save":true,"update":true,"index":true,"excelimport":true,"delete":true},
      "customer":{"read":true,"teamsave":true,"save":true,"update":true,"index":true,"nearbyCustomer":true,"excelimport":true,"dealStatus":true,"putinpool":true,"delete":true,"transfer":true,"excelexport":true,"lock":true}
    }, // 客户管理
    bi: {}, // 商业智能
    manage: {
      "init":{"initData":true},
      "hrm":{"insurance":true,"archives":true,"field":true,"appraisal":true,"salary":true,"params":true},
      "examineFlow":{"update":true},
      "work":{"update":true},
      "adminLog":{"actionRecord":true,"systemLog":true,"loginLog":true},
      "permission":{"update":true},"configSet":{"read":true,"update":true},
      "users":{"deptSave":true,"deptDelete":true,"read":true,"userEnables":true,"userUpdate":true,"userSave":true,"deptUpdate":true},
      "oa":{"examine":true},"system":{"read":true,"update":true},"jxc":{"field":true,"params":true},
      "crm":{"print":true,"field":true,"achievement":true,"pool":true,"activityForm":true,"setting":true}
    }, // 管理后台
    oa: {
      "calendar":{},
      "taskExamine":{},
      "log":{},
      "book":{"read":true},
      "announcement":{"save":true,"update":true,"delete":true}
    }, // 办公
    project: {"projectManage":{"save":true}}, // 项目管理
    hrm: {
      "insurance":{"read":true,"manage":true},
      "recruit":{"read":true,"updatePost":true,"save":true,"savePost":true,"delete":true,"updatePostStatus":true,"readPost":true,"manage":true},
      "appraisal":{"read":true,"stop":true,"readEmp":true,"save":true,"update":true,"delete":true},
      "dept":{"read":true,"save":true,"update":true,"index":true,"delete":true},
      "employee":{"againOnboarding":true,"read":true,"confirmEntry":true,"setInsured":true,"save":true,"update":true,"index":true,"cancelLevel":true,"excelimport":true,"delete":true,"excelexport":true,"leave":true,"changePost":true,"become":true,"promotion":true},
      "salary":{"sendSlip":true,"queryArchives":true,"index":true,"updateArchives":true,"history":true,"manage":true,"queryRecord":true},
      "attendance":{"excelexport":true,"readClock":true}
    }, // 人力资源
    custom: {
      "hrm":
          {
            "insurance":{"read":true,"manage":true},
            "recruit":{"read":true,"updatePost":true,"save":true,"savePost":true,"delete":true,"updatePostStatus":true,"readPost":true,"manage":true},
            "appraisal":{"read":true,"stop":true,"readEmp":true,"save":true,"update":true,"delete":true},
            "dept":{"read":true,"save":true,"update":true,"index":true,"delete":true},
            "employee":{"againOnboarding":true,"read":true,"confirmEntry":true,"setInsured":true,"save":true,"update":true,"index":true,"cancelLevel":true,"excelimport":true,"delete":true,"excelexport":true,"leave":true,"changePost":true,"become":true,"promotion":true},
            "salary":{"sendSlip":true,"queryArchives":true,"index":true,"updateArchives":true,"history":true,"manage":true,"queryRecord":true},
            "attendance":{"excelexport":true,"readClock":true}
            },
      "oa":{
        "calendar":{},
        "taskExamine":{},
        "log":{},
        "book":{"read":true},
        "announcement":{"save":true,"update":true,"delete":true}
        },
      "firstModel":"",
      "work":{
        "project":{"setWork":true,"setTaskOwnerUser":true,"deleteTaskFile":true,"saveTaskClass":true,"deleteTaskClass":true,
          "saveTaskRelation":true,"updateClassOrder":true,"saveTask":true,"setTaskTime":true,"setTaskPriority":true,"updateChildTask":true,
          "setTaskLabel":true,"restoreTask":true,"setTaskDescription":true,"setChildTaskStatus":true,"setTaskMainUser":true,"setTaskOrder":true,
          "excelImport":true,"deleteChildTask":true,"archiveTask":true,"cleanTask":true,"manageTaskOwnerUser":true,"excelExport":true,"setTaskStatus":true,
          "setTaskTitle":true,"addChildTask":true,"deleteTask":true,"updateTaskClass":true,"uploadTaskFile":true}},
      "bi":{
        "call":{"index":true,"analysis":true},
        "product":{"read":true},"oa":{"read":true},
        "business":{"read":true},
        "jxc":{"purchasingStatistics":{"read":true},"productStatistics":{"read":true},"saleStatistics":{"read":true}},
        "achievement":{"read":true},"contract":{"read":true},"ranking":{"read":true},"portrait":{"read":true},"customer":{"read":true}
        },
      "project":{"projectManage":{"save":true}},
      "crm":{
        "product":{"read":true,"transfer":true,"excelexport":true,"save":true,"update":true,"index":true,"excelimport":true,"delete":true,"status":true},
        "business":{"print":true,"read":true,"transfer":true,"teamsave":true,"excelexport":true,"save":true,"update":true,"index":true,"delete":true},
        "contract":{"discard":true,"print":true,"read":true,"transfer":true,"teamsave":true,
          "excelexport":true,"save":true,"update":true,"index":true,"delete":true},
        "pool":{"receive":true,"excelexport":true,"index":true,"distribute":true,"delete":true},
        "outwork":{"read":true,"save":true,"delete":true,"setting":true},
        "marketing":{"read":true,"updateStatus":true,"save":true,"index":true,"update":true,"delete":true},
        "receivablesPlan":{"read":true,"excelexport":true,"save":true,"update":true,"index":true,"delete":true},
        "leads":{"transform":true,"read":true,"transfer":true,"excelexport":true,"save":true,"update":true,"index":true,"excelimport":true,"delete":true},
        "receivables":{"print":true,"read":true,"transfer":true,"teamsave":true,"excelexport":true,"save":true,"update":true,"index":true,"delete":true},
        "visit":{"read":true,"save":true,"update":true,"index":true,"delete":true},
        "invoice":{"read":true,"transfer":true,"resetInvoiceStatus":true,"updateInvoiceStatus":true,"save":true,"update":true,"index":true,"delete":true},
        "followRecord":{"read":true,"excelexport":true,"save":true,"update":true,"excelimport":true,"delete":true},
        "contacts":{"read":true,"transfer":true,"teamsave":true,"excelexport":true,"save":true,"update":true,"index":true,"excelimport":true,"delete":true},
        "customer":{"read":true,"teamsave":true,"save":true,"update":true,"index":true,"nearbyCustomer":true,"excelimport":true,"dealStatus":true,"putinpool":true,"delete":true,"transfer":true,"excelexport":true,"lock":true}
        },
      "manage":{
        "init":{"initData":true},
        "hrm":{"insurance":true,"archives":true,"field":true,"appraisal":true,"salary":true,"params":true},
        "examineFlow":{"update":true},
        "work":{"update":true},
        "adminLog":{"actionRecord":true,"systemLog":true,"loginLog":true},
        "permission":{"update":true},"configSet":{"read":true,"update":true},
        "users":{"deptSave":true,"deptDelete":true,"read":true,"userEnables":true,"userUpdate":true,"userSave":true,"deptUpdate":true},
        "oa":{"examine":true},"system":{"read":true,"update":true},"jxc":{"field":true,"params":true},
        "crm":{"print":true,"field":true,"achievement":true,"pool":true,"activityForm":true,"setting":true}
      }}
  }),
  getters: {


  },
  actions: {
    // 登录
    async Login(userInfo) {
      return new Promise((resolve, reject) => {
        loginAPI(userInfo).then(res => {
          const data = res.data.data || {}
          if (!data.hasOwnProperty('companyList')) {
            this.SET_AUTH(data)
            this.GetUserInfo()
          }
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取权限
    async getAuth() {
      return new Promise((resolve, reject) => {
        adminIndexAuthListAPI().then((response) => {
          const data = response.data
          Lockr.set('authList', data)
          data.wkFirstModel = data.firstModel
          this.SET_ALLAUTH(data)
          this.SET_CRM(data.crm)
          this.SET_BI(data.bi)
          this.SET_MANAGE(data.manage)
          this.SET_OA(data.oa)
          this.SET_PROJECT(data.project)
          this.SET_HRM(data.hrm)

          // 获取 管理后台 员工和部门信息
          this.GetUserList()
          this.GetDeptList()
          if (data.hrm) {
            this.GetHrmUserList()
            this.GetHrmDeptList()
          }

          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    async GetUserInfo() {
      return new Promise((resolve, reject) => {
        adminUsersReadAPI().then(response => {
          // 邮件信息 走之前的逻辑
          this.SET_USERINFO(response.data.data)
          this.SystemLogoAndName()
          request(response.data.data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    async LogOut() {
      return new Promise((resolve, reject) => {
        logoutAPI().then(() => {
          /** flush 清空localStorage .rm('authKey') 按照key清除 */
          removeAuth()
          resetRouter()
          resolve()
        }).catch(error => {
          removeAuth()
          resetRouter()
          reject(error)
        })
      })
    },

    //改成debounce插件来实现，见最底部
    debounceGetUserList ()  {
      this.GetUserList()
    },

    // 管理后台员工列表
    async GetUserList() {
      return new Promise((resolve, reject) => {
        userListAPI({
          pageType: 0
        }).then(res => {
          this.SET_USERLIST(res.data.data.list || [])
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    //改成debounce插件来实现，见最底部
    debounceGetDeptList ()  {
      this.GetDeptList()
    },

    // 管理后台部门列表
    async GetDeptList() {
      return new Promise((resolve, reject) => {
        depListAPI({type: 'tree'}).then(res => {
          console.log("GetDeptList", res.data)
          this.SET_DEPTLIST(res.data.data || [])
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

  SET_USERINFO(userInfo) {
    this.userInfo = userInfo
    localStorage.setItem('loginUserInfo', JSON.stringify(userInfo))
  },
  SET_ALLAUTH(allAuth) {
    this.allAuth = allAuth
  },
  SET_CRM(crm) {
    this.crm = crm
  },
  SET_BI(bi) {
    this.bi = bi
  },
  SET_MANAGE(manage) {
    this.manage = manage
  },
  SET_OA(oa) {
    this.oa = oa
  },
  SET_PROJECT(project) {
    this.project = project
  },
  SET_HRM(hrm) {
    this.hrm = hrm
  },
  SET_AUTH(data) {
    const token = data.adminToken
    Lockr.set('Admin-Token', token);
    addAuth(token)
  },
  SET_USERLIST(data) {
    this.userList = data
  },
  SET_DEPTLIST(data) {
    this.deptList = data
  }
  },
  debounce: {
    // 将动作 searchContacts 防抖 300ms
    debounceGetUserList: 3000,
    debounceGetDeptList: 3000,
  },
})